#include "SpdLogger.h"
#include "Tracer.h"
#include <spdlog/sinks/rotating_file_sink.h>
#include <spdlog/fmt/bin_to_hex.h>
#include <spdlog/formatter.h>
namespace libembx{
SpdLogger::SpdLogger()
{
}

SpdLogger::~SpdLogger()
{
}

bool SpdLogger::init(const std::string& logDir)
{
    if (!Directory::exists(logDir))
    {
        if(!Directory::createDir(logDir,true))
        {
            return false;
        }
    }
    m_logDir = logDir;
    return true;
}

bool SpdLogger::createLog(const std::string& name,uint32 limitSize,uint32 rotations)
{
    if (name.empty() || m_logDir.empty())
    {
        return false;
    }
    std::string logFile = m_logDir+"/";
    logFile.append(name).append(".log");
    if (m_logMap.find(name)!=m_logMap.end())
    {
        TRACE_ERR_CLASS("log[%s] allready exist!\n",CSTR(logFile));
        return false;
    }
    try
	{
        auto logger = spdlog::rotating_logger_mt(name, logFile, limitSize, rotations);
        if (!logger)
        {
            return false;
        }
        m_logMap.emplace(std::make_pair(name,logger));

	}
	catch(const spdlog::spdlog_ex& ex)
	{
		TRACE_ERR_CLASS("create log[%s] error:%s\n",CSTR(logFile),ex.what());
		return false;
	}
    return true;
}

void SpdLogger::logInfo(const std::string& name, const std::string& info)
{
    auto iter = m_logMap.find(name);
    if (iter!=m_logMap.end())
    {
        iter->second->info("{}",info);
    }
}
void SpdLogger::logError(const std::string& name, const std::string& error)
{
    auto iter = m_logMap.find(name);
    if (iter!=m_logMap.end())
    {
        iter->second->error("{}",error);
    }
}
}